#!/usr/bin/env python3
# _*_ coding: utf-8 _*_


from ctypes import *
import platform


class PyFile(Structure):
    """
    对应C中的FILE结构体
    """
    _fields_ = [("_ptr", c_char_p),
                ("_cnt", c_int),
                ("_base", c_char_p),
                ("_flag", c_int),
                ("_file", c_int),
                ("_charbuf", c_int),
                ("_bufsiz", c_int),
                ("_tmpfname", c_char_p)]


class PyIDentry(Structure):
    _fields_ = [("IDname", c_char_p),
                ("length", c_int)]


class _Opaque(Structure):
    """
    Used soley for passing the pointer to the smoapu struct to API
    """    
    _fields_ = [("name", c_char_p),                     # file path/name
                ("file", POINTER(PyFile)),              # FILE structure pointer
                ("elementNames", POINTER(PyIDentry)),   # array of pointers to element names
                ("Nperiods", c_long),                   # number of reporting periods
                ("FlowUnits", c_int),                   # flow units code
                ("Nsubcatch", c_int),                   # number of subcatchments
                ("Nnodes", c_int),                      # number of nodes
                ("Nlinks", c_int),                      # number of links
                ("Npolluts", c_int),                    # number of pollutes
                ("SubcatchVars", c_int),                # number of subcatch reporting variable
                ("NodeVars", c_int),
                ("LinkVars", c_int),
                ("SysVars", c_int),
                ("StartDate", c_double),                # start date of simulation
                ("ReportStep", c_int),                  # reporting time step (seconds)
                ("IDPos", c_longlong),                  # file position where object ID names start
                ("ObjPropPos", c_longlong),             # file position where object properties start
                ("ResultsPos", c_longlong),             # file position where results start
                ("BytesPerPeriod", c_longlong),         # bytes used for results in each period
                ]


if __name__ == '__main__':
	# 普通结构体
	if platform.system() == 'Windows':
		lib_ext = '.dll'
	elif platform.system() == 'Linux':
		lib_ext = '.so'
	elif platform.system() == 'Darwin':
		lib_ext = '.dylib'
	libname = './libswmmoutputapi' + lib_ext
	library = cdll.LoadLibrary(libname)

	outfile = create_string_buffer(b'base_J1.out')
	library.SMO_init.restype = POINTER(_Opaque)
	smoapi = library.SMO_init()
	errNO = library.SMO_open(smoapi, outfile)
	# print(smoapi.name)
	# print(smoapi.Nperiodd)
	print(smoapi.__dict__)
	print("Open ERR: " + str(errNO))

	NodeIDs = {}
	nodeCount = c_int()
	library.SMO_getProjectSize(smoapi, 1, byref(nodeCount))
	print(nodeCount.value)
	# for i in range(library.SMO_getProjectSize(smoapi, ))

	err_close = library.SMO_close(smoapi)
	print("Close Err: " + str(err_close))
